package com.hubei.control;

import com.hubei.service.UserService;
import com.hubei.vo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 陈真
 * @date 2025/6/24-9:07
 * Controller层的作用，完成用户的请求、进行响应处理
 */
@WebServlet("/login.action")
public class LoginControl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 获取前端传递过来的参数
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        // 创建服务层对象，完成相应的业务逻辑处理
        UserService service = UserService.getInstance();
        Users users = new Users();
        users.setUsername(username);
        users.setPassword(password);
        users = service.userLogin(users);
        // 根据业务逻辑处理完成后的结果，进行不同页面的展示
        if (users == null){
            request.setAttribute("loginErr","用户名或密码不正确！");
            // 请求转发
            request.getRequestDispatcher("./login.jsp").forward(request,response);
        }else {
            // 借助于session会话对象
            HttpSession session = request.getSession();
            session.setAttribute("userInfo",users);
            response.sendRedirect("./main.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
